/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.group;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.Groups;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.TextView;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.util.CloseableUtil;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.friend.GroupItem;

public class GroupSelectionActivity extends ListActivity {
    
    private GroupAdapter adapter;
    public static final String ID = "i";
    private ArrayList<GroupItem> groupSelection;
    
    public static final String SELECTED_GROUPS = "sg";
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        setContentView(R.layout.privacy_group_setup);
        findViewById(R.id.actionStub).setVisibility(View.VISIBLE);
        
        ((TextView)findViewById(android.R.id.text1)).setText("Please select the groups you wish!");
        
        ((Button)findViewById(android.R.id.button1)).setVisibility(View.INVISIBLE);
        
        Button next = (Button)findViewById(android.R.id.button2);
        next.setText("Done Selecting");
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ListView lv = getListView();
                final SparseBooleanArray sp = lv.getCheckedItemPositions();
                final ArrayList<GroupItem> list = adapter.groups;
                groupSelection = new ArrayList<GroupItem>();
                
                int size = list.size();
                for(int i = 0; i < size; i++) {
                    if(sp.get(i)) {
                        groupSelection.add(list.get(i));
                    }
                }
                
                if(groupSelection.size() > 0) {
                    Intent i = new Intent();
                    i.getExtras().putSerializable(SELECTED_GROUPS, groupSelection);
                    setResult(RESULT_OK, i);
                    finish();
                } else {
                    new AlertDialog.Builder(GroupSelectionActivity.this)
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setTitle("No Group Selection")
                            .setMessage("Please select at least one group to proceed.")
                            .setPositiveButton("OK", null)
                    .create().show();
                }
            }
        });
        
        View empty = LayoutInflater.from(this).inflate(R.layout.empty_progress, null);
        ((TextView)empty.findViewById(android.R.id.text1)).setText("Please wait while we load your groups.");
        
        final ListView lv = getListView();
        lv.setEmptyView(empty);
        lv.setItemsCanFocus(false);
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
        new LoadGroupsTask(this).execute();
    }
    
    static class GroupAdapter extends BaseAdapter {
        private ArrayList<GroupItem> groups;
        private LayoutInflater inflater;

        public GroupAdapter(Context c, ArrayList<GroupItem> groups) {
            this.groups = groups;
            this.inflater = LayoutInflater.from(c);
        }

        public int getCount() {
            return groups.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }
        
        public View getView(int position, View cv, ViewGroup parent) {
            ViewHolder holder;
            if(cv == null) {
                cv = inflater.inflate(R.layout.check_list_item_2line, parent, false);
                holder = new ViewHolder();
//                holder.icon1    = (ImageView)cv.findViewById(android.R.id.icon1);
                holder.checkbox = (CheckedTextView)cv.findViewById(android.R.id.text1);//text1 is just because there is no checkbox1
                holder.text1    = (TextView)cv.findViewById(android.R.id.title);
//                holder.text2    = (TextView)cv.findViewById(android.R.id.summary);
                
                cv.setTag(holder);
            } else {
                holder = (ViewHolder)cv.getTag();
            }
            
            final GroupItem gi = groups.get(position);
            holder.text1.setText("Group: " + gi.name);
            
            holder.checkbox.setVisibility(View.VISIBLE);
            
            return cv;
        }
        
        static class ViewHolder {
            CheckedTextView checkbox;
            TextView text1, text2;
        }
    }
    
    class LoadGroupsTask extends NetworkHandlerTask<Void, ArrayList<GroupItem>, Void> {
        private Context c;
        LoadGroupsTask(Context c) {
            this.c = c;
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @SuppressWarnings("unchecked")
        @Override
        protected Void doInBackground(Void... params) {

            final ContentResolver cr = c.getContentResolver();
            final ArrayList<GroupItem> list = new ArrayList<GroupItem>();
            Cursor c = null;
            try {
                
                Intent i = getIntent();
                c = cr.query(Groups.CONTENT_URI, null, Groups._ID + " <> ? AND " +  Groups.NAME + " not in (?)", 
                        new String[]{"" + i.getIntExtra(ID, 0), "System Group: My Contacts"}, Groups.NAME);
                int id, name;
                if (c != null && c.moveToFirst()) {
                    id    = c.getColumnIndex(Groups._ID);
                    name  = c.getColumnIndex(Groups.NAME);
                    do {
                        list.add(new GroupItem(c.getInt(id), c.getString(name)));
                    } while (c.moveToNext());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                CloseableUtil.safeClose(c);
                c = null;
            }

            publishProgress(list);
            return null;
        }
        
        @Override
        protected void onProgressUpdate(ArrayList<GroupItem>... values) {
            super.onProgressUpdate(values);
            final ArrayList<GroupItem> list = values[0];
            adapter = new GroupAdapter(c, list);
            final ListView elv = getListView();
            elv.setAdapter(adapter);
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }
}
